package com.two.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.two.core.entity.AclPermission;
import com.two.core.entity.AclRolePermission;
import com.two.core.util.JWTUtil;
import com.two.core.util.MyListPage;
import com.two.core.vo.Page;
import com.two.core.vo.Result;
import com.two.security.util.WebUtils;
import com.two.system.dao.AclPermissionDao;
import com.two.system.service.AclPermissionService;
import com.two.system.service.AclRolePermissionService;
import com.two.system.vo.FenPermissionVo;
import com.two.system.vo.PermissionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AclPermissionServiceImpl implements AclPermissionService {

    @Autowired
    private AclPermissionDao permissionDao;

    @Autowired
    private AclRolePermissionService rolePermissionService;

    @Override
    public Result findByUserId(String userid) {
        List<AclPermission> aclPermissions = permissionDao.selectByUserid(userid);
        return new Result<List<AclPermission>>(2000,"查询成功",aclPermissions);
    }
    @Override
    public Result<List<AclPermission>> findByUsername() {
        //1.得到当前用户的名称
        String token = WebUtils.getRequest().getHeader("token");
        Map<String, Object> map = JWTUtil.getTokenChaim(token);
        String username = (String) map.get("username");

        //2.调用dao中根据用户名查询该用户具有的菜单。
        List<AclPermission> permissions = permissionDao.selectByUsername(username);


        //1. 查询一级菜单
        List<AclPermission> first=new ArrayList<>();
        for(AclPermission permission:permissions){
            if(permission.getPid().equals("1")){
                first.add(permission);
            }
        }
        //2. 查询一级菜单下的子菜单
        for(AclPermission f:first){
            f.setChildren(findChildren(permissions,f.getId()));
        }
        return new Result<>(2000,"查询左侧菜单成功",first);
    }
    @Override
    public Result<Map<String, Object>> findAll(String roleId) {
        //获取所有权限
        List<AclPermission> permissions = permissionDao.selectList(null);
        //1.得到一级菜单
        List<AclPermission> first=new ArrayList<>();
        for(AclPermission permission:permissions){
            if(permission.getPid().equals("1")){
                first.add(permission);
            }
        }
        //2.设置一级菜单的相应子菜单
        for(AclPermission p:first){
            p.setChildren(findChildren(permissions,p.getId()));
        }

        //获取当前角色具有的权限id
        List<String> perIds=permissionDao.selectByRoleId(roleId);


        Map<String,Object> map=new HashMap<>();
        map.put("allPermissions",first);
        map.put("checkItems",perIds);

        return new Result<>(2000,"查询成功",map);
    }
    @Override
    @Transactional
    public Result confirmFenPermission(FenPermissionVo fenPermissionVo) {
        //根据角色id删除原来的具有的权限id
        UpdateWrapper<AclRolePermission> wrapper=new UpdateWrapper<>();
        wrapper.eq("role_id",fenPermissionVo.getRoleId());
        rolePermissionService.remove(wrapper);

        //批量添加角色具有的权限
        List<AclRolePermission> list=new ArrayList<>();
        for (String permissionId:fenPermissionVo.getPermissionIds()){
            AclRolePermission aclRolePermission = new AclRolePermission();
            aclRolePermission.setIsDeleted(0);
            aclRolePermission.setGmtCreate(LocalDateTime.now());
            aclRolePermission.setGmtModified(LocalDateTime.now());
            aclRolePermission.setPermissionId(permissionId);
            aclRolePermission.setRoleId(fenPermissionVo.getRoleId());
            list.add(aclRolePermission);
        }
        rolePermissionService.saveBatch(list);

        return new Result(2000,"分配权限成功");
    }
    @Override
    public Result findByConditionPage(PermissionVo permissionVo, Integer current, Integer pageSize) {
        QueryWrapper<AclPermission> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(permissionVo.getName())){
            wrapper.like("name",permissionVo.getName());
        }
        wrapper.in("type",1,2,3);
        List<AclPermission> permissions =permissionDao.selectList(wrapper);

//        //得到当前用户的名称
//        String token = WebUtils.getRequest().getHeader("token");
//        Map<String, Object> map = JWTUtil.getTokenChaim(token);
//        String username = (String) map.get("username");
//        //调用dao中根据用户名查询该用户具有的菜单。
//        List<AclPermission> permissions =null;
//        if (StringUtils.hasText(permissionVo.getName())){
//            String name="%"+permissionVo.getName()+"%";
//            permissions=permissionDao.selectIdsByUsername(username,name);
//        }else {
////            permissions=permissionDao.selectByUsername(username);
//            permissions=permissionDao.selectAll(username);
//        }
        //1. 查询一级菜单
        List<AclPermission> first=new ArrayList<>();
        //拿到所有id
        List<String> ids=new ArrayList<>();
        for (AclPermission permission : permissions) {
            ids.add(permission.getId());
        }
        //1. 根据父亲是否存在添加一级菜单
        for (AclPermission permission : permissions) {
            if (!ids.contains(permission.getPid()) || permission.getPid()=="1"){
                first.add(permission);
            }
        }
//        2. 查询一级菜单下的子菜单
        for(AclPermission f:first){
            f.setChildren(findChildren(permissions,f.getId()));
        }
        Page page = MyListPage.startPage(first, current, pageSize);
        return new Result<>(2000,"查询菜单成功",page);
    }

    @Override
    public Result insert(AclPermission permission){
        permission.setGmtCreate(LocalDateTime.now());
        int i = 0;
        String msg = "";
        if (permission.getId()!=null){
            permission.setGmtModified(LocalDateTime.now());
            i = permissionDao.updateById(permission);
            msg="修改";
        }else {
            permission.setGmtCreate(LocalDateTime.now());
            permission.setGmtModified(LocalDateTime.now());
            i = permissionDao.insert(permission);
            msg="添加";
        }
        if (i > 0) {
            return new Result(2000,msg+"成功");
        }
        return new Result(5000,msg+"失败");
    }

    @Override
    public Result deleteById(List<String> ids) {
        UpdateWrapper<AclPermission> wrapper = new UpdateWrapper<>();
        wrapper.in("id",ids);
        int i = permissionDao.delete(wrapper);
        if (i >0) {
            return new Result<>(2000,"删除成功");
        }
        return new Result<>(5000,"删除失败");
    }

    //3.方法的递归
    private List<AclPermission> findChildren(List<AclPermission> permissions, String id) {
        List<AclPermission> seconds=new ArrayList<>();
        for(AclPermission p:permissions){
            if(p.getPid().equals(id)){
                seconds.add(p);
            }
        }

        for(AclPermission p :seconds){
            p.setChildren(findChildren(permissions,p.getId()));
        }
        return seconds;
    }

}